package org.jeecg.modules.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.util.FindsDistrictChildrenUtil;
import org.jeecg.modules.data.entity.District;
import org.jeecg.modules.data.entity.DistrictTree;
import org.jeecg.modules.data.mapper.DistrictMapper;
import org.jeecg.modules.data.service.IDistrictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * @Description: district
 * @Author: jeecg-boot
 * @Date:   2025-04-14
 * @Version: V1.0
 */
@Service
public class DistrictServiceImpl extends ServiceImpl<DistrictMapper, District> implements IDistrictService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public District getAreaCode(String areaName) {
        return this.baseMapper.getAreaCode(areaName);	}

    @Override
    public District getCityCode(String cantCode) {
        return this.baseMapper.getCityCode(cantCode);
    }

    @Override
    public List<DistrictTree> queryTreeList() {
        LambdaQueryWrapper<District> query = new LambdaQueryWrapper<District>();
        query.orderByAsc(District::getCantCode);
        List<District> list = this.list(query);
        this.setUserIdsByDisList(list);
        List<DistrictTree> listResult = FindsDistrictChildrenUtil.wrapTreeDataToTreeList(list);
        return listResult;
    }

    @Override
    public List<DistrictTree> queryTreeList(String ids) {
        List<DistrictTree> listResult=new ArrayList<>();
        LambdaQueryWrapper<District> query = new LambdaQueryWrapper<District>();
        if(oConvertUtils.isNotEmpty(ids)){
            query.in(true,District::getCantCode,ids.split(","));
        }
        query.orderByAsc(District::getCantCode);
        List<District> list = this.list(query);
        for (District district : list) {
            listResult.add(new DistrictTree(district));
        }
        return listResult;
    }

    /**
     * 设置用户id，用于前台展示
     * @param disList 集合
     */
    private void setUserIdsByDisList(List<District> disList) {
        //查询不为空的情况
        LambdaQueryWrapper<SysUser> query  = new LambdaQueryWrapper<>();
        query.isNotNull(SysUser::getDisIds);
        List<SysUser> users = sysUserMapper.selectList(query);
        Map<String,Object> map = new HashMap(5);
        //先循环一遍找到不同的负责部门id
        for (SysUser user:users) {
            String disIds = user.getDisIds();
            String[] disIdArray = disIds.split(",");
            for (String disId:disIdArray) {
                //mao中包含部门key，负责用户直接拼接
                if(map.containsKey(disId)){
                    String userIds = map.get(disId) + "," + user.getId();
                    map.put(disId,userIds);
                }else{
                    map.put(disId,user.getId());
                }
            }
        }
        //循环部门集合找到部门id对应的负责用户
        for (District district:disList) {
            if(map.containsKey(district.getCantCode())){
                district.setDirectorUserIds(map.get(district.getCantCode()).toString());
            }
        }
    }




    @Override
    public List<District> queryTreeListNoPage(QueryWrapper<District> queryWrapper) {
        List<District> dataList = baseMapper.selectList(queryWrapper);
        List<District> mapList = new ArrayList<>();
        for(District data : dataList){
            String pidVal = data.getPid();
            //递归查询子节点的根节点
            if(pidVal != null && !IDistrictService.NOCHILD.equals(pidVal)){
                District rootVal = this.getTreeRoot(pidVal);
                if(rootVal != null && !mapList.contains(rootVal)){
                    mapList.add(rootVal);
                }
            }else{
                if(!mapList.contains(data)){
                    mapList.add(data);
                }
            }
        }
        return mapList;
    }


	/**
     * 递归查询节点的根节点
     * @param pidVal
     * @return
     */
    private District getTreeRoot(String pidVal){
        District data =  baseMapper.selectOne(new QueryWrapper<District>().eq("cant_code", pidVal));
        if(data != null && !IDistrictService.ROOT_PID_VALUE.equals(data.getPid())){
            return this.getTreeRoot(data.getPid());
        }else{
            return data;
        }
    }

    /**
     * 根据id查询所有子节点id
     * @param ids
     * @return
     */
    private String queryTreeChildIds(String ids) {
        //获取id数组
        String[] idArr = ids.split(",");
        StringBuffer sb = new StringBuffer();
        for (String pidVal : idArr) {
            if(pidVal != null){
                if(!sb.toString().contains(pidVal)){
                    if(sb.toString().length() > 0){
                        sb.append(",");
                    }
                    sb.append(pidVal);
                    this.getTreeChildIds(pidVal,sb);
                }
            }
        }
        return sb.toString();
    }

    /**
     * 递归查询所有子节点
     * @param pidVal
     * @param sb
     * @return
     */
    private StringBuffer getTreeChildIds(String pidVal,StringBuffer sb){
        List<District> dataList = baseMapper.selectList(new QueryWrapper<District>().eq("pid", pidVal));
        if(dataList != null && dataList.size()>0){
            for(District tree : dataList) {
                if(!sb.toString().contains(tree.getCantCode())){
                    sb.append(",").append(tree.getCantCode());
                }
                this.getTreeChildIds(tree.getCantCode(),sb);
            }
        }
        return sb;
    }

}
